// 用户战绩页面逻辑
const app = getApp()

Page({
  data: {
    userInfo: null,
    userStats: {
      wins: 0,
      losses: 0,
      winRate: 0,
      rank: 0
    },
    records: [],
    collapsedDates: {}, // 记录哪些日期被折叠了
    loading: false,
    hasMore: true,
    currentPage: 1,
    pageSize: 10 // 每页显示10天的数据
  },

  // 分享给好友
  async onShareAppMessage() {
    const ShareUtil = require('../../utils/shareUtil')
    return await ShareUtil.generateShareAppMessageConfig('user-records', {
      userInfo: this.data.userInfo,
      userStats: this.data.userStats
    })
  },

  // 分享到朋友圈
  async onShareTimeline() {
    const ShareUtil = require('../../utils/shareUtil')
    return await ShareUtil.generateShareTimelineConfig('user-records', {
      userInfo: this.data.userInfo,
      userStats: this.data.userStats
    })
  },

  onLoad() {
    this.loadUserInfo()
    this.loadUserStats()
    this.loadRecords()
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || app.globalData.userInfo
    if (userInfo) {
      this.setData({ userInfo })
    }
  },

  // 加载用户战绩
  loadUserStats() {
    if (!this.data.userInfo) {
      return
    }

    wx.request({
      url: `${app.globalData.baseUrl}/api/user/stats`,
      method: 'GET',
      data: {
        user_id: this.data.userInfo.id
      },
      success: (res) => {
        if (res.data.success) {
          // 使用接口返回的 totalScore，确保与历史记录一致
          this.setData({
            userStats: res.data.data,
            // 更新用户信息中的总积分，使用计算出的值
            'userInfo.total_score': res.data.data.totalScore || this.data.userInfo?.total_score || 0
          })
        }
      },
      fail: (err) => {
        console.error('获取用户战绩失败:', err)
      }
    })
  },

  // 加载历史记录
  loadRecords() {
    if (!this.data.userInfo || this.data.loading) {
      return
    }

    this.setData({ loading: true })

    wx.request({
      url: `${app.globalData.baseUrl}/api/user/records`,
      method: 'GET',
      data: {
        user_id: this.data.userInfo.id,
        page: this.data.currentPage,
        page_size: this.data.pageSize
      },
      success: (res) => {
        if (res.data.success) {
          const newRecords = res.data.data.records || []
          
          // 如果是第一页，直接替换；否则追加
          const records = this.data.currentPage === 1 ? newRecords : [...this.data.records, ...newRecords]
          
          // 初始化折叠状态（新加载的日期默认展开）
          const collapsedDates = { ...this.data.collapsedDates }
          
          this.setData({
            records: records,
            hasMore: res.data.data.has_more || false,
            collapsedDates: collapsedDates
          })
        }
      },
      fail: (err) => {
        console.error('获取历史记录失败:', err)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        currentPage: this.data.currentPage + 1
      })
      this.loadRecords()
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      currentPage: 1,
      records: [],
      collapsedDates: {} // 重置折叠状态
    })
    this.loadUserStats()
    this.loadRecords()
    wx.stopPullDownRefresh()
  },

  // 切换日期折叠状态
  toggleDay(e) {
    const date = e.currentTarget.dataset.date
    const collapsedDates = { ...this.data.collapsedDates }
    collapsedDates[date] = !collapsedDates[date]
    this.setData({
      collapsedDates: collapsedDates
    })
  }
})
